package header;

import java.io.*;
import java.awt.*;

// Handles all the details related to maps
public class MapHandler {
	
	int[][] map;
	int x, y;
	int tileSize;
	int mapWidth;
	int mapHeight;
	String name;
	int playerX, playerY;
	
	public int getTileSize() { return tileSize; }
	public void setMap(int i, int j, int val) {
		map[i][j] = val;
	}
	
	public MapHandler(String s, int tileSize) {
		this.name = s;
		this.tileSize = tileSize;

		try {
			BufferedReader br = new BufferedReader(new FileReader(s));
			mapWidth = Integer.parseInt(br.readLine());
			mapHeight = Integer.parseInt(br.readLine());
			map = new int[mapHeight][mapWidth];

			String delimiters = " ";
			for(int row = 0; row < mapHeight; row++) {
				String line = br.readLine();
				String[] tokens = line.split(delimiters);
				for(int col = 0; col < mapWidth; col++) {
					map[row][col] = Integer.parseInt(tokens[col]);
				}
			}
			br.close();
		} catch (Exception e) {
		}
	}
	
	public void save() {
		try {
			BufferedWriter br = new BufferedWriter(new FileWriter(name));
			String output = "" + mapWidth;
			br.write(output);
			br.newLine();
			output = "" + mapHeight;
			br.write(output);
			br.newLine();
			for (int row = 0; row < mapHeight; row++) {
				for (int col = 0; col < mapWidth; col++) {
					output = "" + map[row][col] + " ";
					br.write(output);
				}
				br.newLine();
			}
			br.close();
		} catch (Exception e) { }
	}
	
	public int getPlayerX() { return playerX; }
	public int getPlayerY() { return playerY; }
	
	public void update() {
	}

	public void draw(Graphics2D g) {
		for(int row = 0; row < mapHeight; row++) {
			for(int col = 0; col < mapWidth; col++) {
				int rc = map[row][col];
				if (rc == 0) 
					g.setColor(Color.BLACK);
				if (rc == 1) 
					g.setColor(Color.WHITE);
				if (rc == 2) {
					g.setColor(Color.RED);
					playerX = row;
					playerY = col;
				}
				if (rc == 3)
					g.setColor(Color.ORANGE);

				g.fillRect(x + col * tileSize, y + row * tileSize, tileSize, tileSize);	
			}
		}
		
		for(int row = 0; row < mapHeight; row++) {
			for(int col = 0; col < mapWidth; col++) {
				g.setColor(g.getColor().darker());
				g.drawRect(x + col * tileSize, y + row * tileSize, tileSize, tileSize);
            }
		}
	}


}
